﻿using Bilibili.Common.Database.Table;
using Bilibili.Common.Log;
using PCLUntils.Json;
using PCLUntils.Objects;
using System;

namespace Bilibili.Common.Database
{
    public sealed class Cache
    {
        private static Cache instance;
        public static Cache Instance
        {
            get
            {
                if (instance == null)
                    instance = new Cache();
                return instance;
            }
        }
        private Cache() { }
        public bool Save(string key, object value)
        {
            try
            {
                using DB db = new DB();
                var entity = db.Connection.Table<CacheDataTab>().FirstOrDefault(x => x.Name == key);
                if (entity.IsNotEmpty())
                {
                    entity.Update(value);
                    db.Connection.Update(entity);
                }
                else
                {
                    entity = new CacheDataTab(key, value);
                    db.Connection.Insert(entity);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("Cache.Save", ex);
                return false;
            }
        }
        public bool GetData<T>(string name, out T value)
        {
            value = default;
            try
            {
                using DB db = new DB();
                var entity = db.Connection.Table<CacheDataTab>().FirstOrDefault(x => x.Name == name);
                if (entity.IsNotEmpty() && entity.Content.IsNotEmpty())
                    return entity.Content.TryParseObject(out value);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("GetData", ex);
            }
            return false;
        }
    }
}